<template>
  <div class="canvas-sidebar h-[100%] overflow-y-auto w-[400px]">
    <TemplateSelector @select="onSelect" :query="query"></TemplateSelector>
  </div>
</template>

<script setup lang="ts">
import { getTemplate, type ITemplate } from '@/api/modules/esl/template';
import { useQuery } from '@/hooks/table';
import { currentComponent, currentTheme } from '../data/data';
import { getMaxIndex } from '../data/canvas.actions';
import { message } from 'ant-design-vue';
import type { ThemeCanvas } from '@/types/theme';
import { nanoid } from 'nanoid';

const query = useQuery<ITemplate>();

const onSelect = async (item: ITemplate) => {
  const { data } = await getTemplate(item.templateId!);
  const jsonData = JSON.parse(data.data.templateData);

  if (jsonData.stage.w > currentTheme.value.width! || jsonData.stage.h > jsonData.stage.height!) {
    message.warning('该组件过大');
    return;
  }
  const newItem: ThemeCanvas = {
    x: 0,
    y: 0,
    w: jsonData.stage.w,
    h: jsonData.stage.h,
    templateId: item.templateId!,
    imageSrc: item.imgSrc,
    id: nanoid(),
    draggable: false,
    resizable: false,
    productIds: [],
    name: item.templateName,
    z: getMaxIndex() || 0 + 1,
    version: 1.0,
    scale: 1,
  };
  currentTheme.value.image.push(newItem);
  currentComponent.value = newItem;
};
</script>

<style lang="scss" scoped></style>
